import * as React from 'react';

import * as Mycss from '../CSS/mycss.css';
import * as StringHelper from '../MyHelper/StringHelper';
import * as Global from '../TS/Global';
import { MessageBox } from './messagebox';
import * as MyCfg from './MyCfg';
import { ServiceEvent } from './serial';

export interface ServiceProps extends Global.Myprops {
    //在数组的索引
    arrIndex?: number;
    Servicefg?: MyCfg.Service_cfg;
    CfgEvent: ServiceEvent
};

export interface ServiceState {
    arrIndex?: number;
    IsOn?: boolean;
    ServiceType?: string;
    NetNum?: string;
    RemoteIP?: string;
    IsspecifyPort?: string;
    RemotePort?: string;
    LocalPort?: string;
    //当前对话框是添加还是编辑
    IsADD?: boolean;
    ISHeartbeat?: boolean; //是否启用心跳包
    Ismodbus?: boolean;
    Heartbeat_Hex?: string; //心跳包字节
    Heartbeat_Interval?: string; //心跳包间隔
    RemoteIP_check?: boolean;
    RemotePort_check?: boolean;
    LocalPort_check?: boolean;
    Heartbeat_Hex_check?: boolean;
    Heartbeat_Interval_check?: boolean;


};

export class Service extends React.Component<ServiceProps,
    ServiceState> {
    constructor(props) {
        super(props);
        console.log("服务初始化" + props.arrIndex);

        //设置状态
        this.state = {
            arrIndex: props.arrIndex != undefined
                ? props.arrIndex
                : -1,
            IsOn: props.Servicefg
                ? props.Servicefg.IsOn
                : true,
            IsADD: false,
            ServiceType: props.Servicefg
                ? props.Servicefg.ServiceType
                : 'UDP',
            NetNum: props.Servicefg
                ? props.Servicefg.NetNum
                : '0',
            RemoteIP: props.Servicefg
                ? props.Servicefg.RemoteIP
                : '192.168.1.100',
            IsspecifyPort: props.Servicefg
                ? props.Servicefg.IsspecifyPort
                : '0',
            RemotePort: props.Servicefg
                ? props.Servicefg.RemotePort
                : '10000',
            LocalPort: props.Servicefg
                ? props.Servicefg.LocalPort
                : '0',
            ISHeartbeat: props.Servicefg
                ? props.Servicefg.ISHeartbeat
                : false, //是否启用心跳包
            Heartbeat_Hex: props.Servicefg
                ? props.Servicefg.Heartbeat_Hex
                : "FF FF", //心跳包字节
            Heartbeat_Interval: props.Servicefg
                ? props.Servicefg.Heartbeat_Interval
                : '5000', //心跳包间隔
            Ismodbus: props.Servicefg
                ? props.Servicefg.Ismodbus
                : false,
            RemoteIP_check: true,
            RemotePort_check: true,
            LocalPort_check: true,
            Heartbeat_Hex_check: true,
            Heartbeat_Interval_check: true
        };

    }

    public CheckPort(obj: string): boolean {
        if (!StringHelper.IsInt(obj)) {
            return false;
        }
        let num: number = parseInt(obj, 10);
        if (num != NaN && num > 99 && num < 65536) {
            return true;
        }
        return false;
    }
    public handleClick(event: any, cmd?: string): void {

        if (cmd == "delservice") {
            console.log('进行删除...');
            this
                .props
                .CfgEvent(this.state, "del");
            return;
        }
        event.preventDefault();
        let name: string = event.currentTarget.name;
        console.log(name);
        if (name == "edit") {
            this.setState({
                IsADD: false
            }, () => {
                $(this.refs.mymodal).modal();
            });

        } else if (name == "add") {
            this.setState({
                IsADD: true,
                ServiceType: "UDP",
                LocalPort: "0"
            }, () => {

                $(this.refs.mymodal).modal();
            });

        } else if (name == "savebtn") {
            let checkedallOK = true;
            let tempck: ServiceState = this.state;

            console.log("保存服务:" + JSON.stringify(this.state));
            if (this.state.ServiceType == "UDP" || this.state.ServiceType == "TCPClient") {
                if (!this.CheckPort(this.state.LocalPort) && parseInt(this.state.LocalPort, 10) != 0) {
                    checkedallOK = false;
                    tempck.LocalPort_check = false;
                }
                if (!StringHelper.IsIP(this.state.RemoteIP) && !StringHelper.IsURL(this.state.RemoteIP)) {
                    checkedallOK = false;
                    tempck.RemoteIP_check = false;
                }
                if (!this.CheckPort(this.state.RemotePort)) {
                    checkedallOK = false;
                    tempck.RemotePort_check = false;
                }
            }
            if (this.state.ServiceType == "TCPServer") {
                if (!this.CheckPort(this.state.LocalPort)) {
                    checkedallOK = false;
                    tempck.LocalPort_check = false;
                }
            }
            if (!StringHelper.IsInt(this.state.Heartbeat_Interval)) {
                checkedallOK = false;
                tempck.Heartbeat_Interval_check = false;
            }
            if (!StringHelper.IsHex(this.state.Heartbeat_Hex)) {
                checkedallOK = false;
                tempck.Heartbeat_Hex_check = false;
            }
            if (checkedallOK) {
                this
                    .props
                    .CfgEvent(this.state);

                $(this.refs.mymodal).modal('hide');
            } else {
                this.setState(tempck);
            }


        } else if (name == "btn_toggle") {
            //禁用还是启用
            let t: boolean = !this.props.Servicefg.IsOn;
            this.setState({
                IsADD: false,
                IsOn: t
            }, () => {
                this
                    .props
                    .CfgEvent(this.state, 'tr');
            });

        } else if (name == "btn_del") {
            console.log("删除确认...");
            let msgbox: any = this.refs.messagebox;
            msgbox.Show();
        }

    }
    public handleChange(event: React.ChangeEvent<any>): void {

        let tcfg: any = {};
        let value: any;
        let isset: boolean = false;
        if (event.target.type == "checkbox") {

            tcfg[event.target.name] = event.target.checked;
            isset = true;
        } else if (event.target.type == "radio") {
            if (event.target.checked) {

                tcfg[event.target.name] = event.target.value;
                isset = true;
            }

        } else if (event.target.type == "select-one") {
            // <option value='0'>全部</option>
            var index = event.target.selectedIndex;
            value = event.target.options[index].value;

        } else {
            value = event.target.value;
        }
        if (!isset) {

            tcfg[event.target.name] = value;
        }
        let namexxx: string = event.target.name;
        if (namexxx == "MaxLength" || namexxx == "Interval" || namexxx == "Heartbeat_Interval" || namexxx == "ModBuspoll_TimeOut") {
            tcfg[namexxx + "_check"] = true;
            if (!StringHelper.IsInt(event.target.value)) {

                tcfg[namexxx + "_check"] = false;
            }

        } else if (namexxx == "Heartbeat_Hex") {
            tcfg[namexxx + "_check"] = true;
            if (!StringHelper.IsHex(event.target.value)) {

                tcfg[namexxx + "_check"] = false;
            }
        } else if (namexxx == "RemotePort") {

            tcfg[namexxx + "_check"] = true;

            var re = /^\d+$/;
            if (!re.test(event.target.value)) {
                tcfg[namexxx + "_check"] = false;
            } else {
                if (!this.CheckPort(event.target.value)) {
                    console.warn("端口错误");
                    tcfg[namexxx + "_check"] = false;
                }
            }

        } else if (namexxx == "RemoteIP") {

            tcfg[namexxx + "_check"] = true;
            if (!StringHelper.IsIP(event.target.value) && !StringHelper.IsURL(event.target.value)) {
                tcfg[namexxx + "_check"] = false;
            }
        } else if (namexxx == "LocalPort") {
            tcfg[namexxx + "_check"] = true;
            if (!this.CheckPort(event.target.value)) {

                tcfg[namexxx + "_check"] = false;

            } else {
                if (this.state.ServiceType == 'TCPServer' && parseInt(event.target.value, 10) == 0) {
                    tcfg[namexxx + "_check"] = false;
                }
            }
            if (this.state.ServiceType == 'UDP' || this.state.ServiceType == 'TCPClient') {
                if (parseInt(event.target.value, 10) == 0) {
                    tcfg[namexxx + "_check"] = true;
                }
            }

        } else if (event.target.value == 'TCPServer') {

            if (this.state.LocalPort == "0") {
                tcfg["LocalPort"] = "10000";
            }
        }
        //RemotePort_check
        this.setState(tcfg);

    }

    componentWillReceiveProps(nextProps) {
        // console.log('componentWillReceiveProps'); 设置状态
        this.setState({
            arrIndex: nextProps.arrIndex != undefined
                ? nextProps.arrIndex
                : -1,
            IsOn: nextProps.Servicefg
                ? nextProps.Servicefg.IsOn
                : true,
            ServiceType: nextProps.Servicefg
                ? nextProps.Servicefg.ServiceType
                : 'UDP',
            NetNum: nextProps.Servicefg
                ? nextProps.Servicefg.NetNum
                : '1',
            RemoteIP: nextProps.Servicefg
                ? nextProps.Servicefg.RemoteIP
                : '192.168.1.100',
            IsspecifyPort: nextProps.Servicefg
                ? nextProps.Servicefg.IsspecifyPort
                : '',
            RemotePort: nextProps.Servicefg
                ? nextProps.Servicefg.RemotePort
                : '',
            LocalPort: nextProps.Servicefg
                ? nextProps.Servicefg.LocalPort
                : '10000',
            ISHeartbeat: nextProps.Servicefg
                ? nextProps.Servicefg.ISHeartbeat
                : false, //是否启用心跳包
            Heartbeat_Hex: nextProps.Servicefg
                ? nextProps.Servicefg.Heartbeat_Hex
                : "FF FF", //心跳包字节
            Heartbeat_Interval: nextProps.Servicefg
                ? nextProps.Servicefg.Heartbeat_Interval
                : '5000', //心跳包间隔
            Ismodbus: nextProps.Servicefg ? nextProps.Servicefg.Ismodbus : false

        });
    }
    public render(): JSX.Element {
        let _ischeck = this.state.Heartbeat_Hex_check && this.state.Heartbeat_Interval_check && this.state.LocalPort_check && this.state.RemoteIP_check && this.state.RemotePort_check;
        let localportview = <div
            className={this.state.LocalPort_check
                ? "form-group "
                : "form-group has-error has-feedback"}>
            <label className="col-xs-3 control-label">{Global.GetLocal("本地端口")}</label>
            <div className="col-xs-8">
                <input
                    type="text"
                    name="LocalPort"
                    className="form-control"
                    placeholder=""
                    data-toggle="tooltip"
                    data-placement="top"
                    data-original-title={Global.GetLocal("本地端口tp")}
                    value={this.state.LocalPort}
                    onChange={e => this.handleChange(e)} />
                <span
                    className={this.state.LocalPort_check
                        ? "hidden"
                        : "glyphicon glyphicon-remove form-control-feedback"}></span>
                <br
                    className={this.state.LocalPort_check
                        ? "hidden"
                        : ""} />
                <div
                    className={this.state.LocalPort_check
                        ? "alert alert-danger hidden"
                        : "alert alert-danger "}
                    role="alert">{Global.GetLocal("端口范围")}</div>
            </div>
        </div>;
        let removeIPview = <div
            className={this.state.RemoteIP_check
                ? "form-group "
                : "form-group has-error has-feedback"}>
            <label className="col-xs-3 control-label">{Global.GetLocal("目的IP地址")}</label>
            <div className="col-xs-8">
                <input
                    type="text"
                    className="form-control"
                    placeholder=" "
                    value={this.state.RemoteIP}
                    name="RemoteIP"
                    onChange={e => this.handleChange(e)} />
                <span
                    className={this.state.RemoteIP_check
                        ? "hidden"
                        : "glyphicon glyphicon-remove form-control-feedback"}></span>
                <br
                    className={this.state.RemoteIP_check
                        ? "hidden"
                        : ""} />
                <div
                    className={this.state.RemoteIP_check
                        ? "alert alert-danger hidden"
                        : "alert alert-danger "}
                    role="alert">{Global.GetLocal("请输入正确的IP")}</div>
            </div>
        </div>;
        let removeportview = <div
            className={this.state.RemotePort_check
                ? "form-group "
                : "form-group has-error has-feedback"}>
            <label className="col-xs-3 control-label">{Global.GetLocal("目的端口")}</label>
            <div className="col-xs-8">
                <input
                    type="text"
                    className="form-control"
                    placeholder=" "
                    value={this.state.RemotePort}
                    name="RemotePort"
                    onChange={e => this.handleChange(e)} />
                <span
                    className={this.state.RemotePort_check
                        ? "hidden"
                        : "glyphicon glyphicon-remove form-control-feedback"}></span>
                <br
                    className={this.state.RemotePort_check
                        ? "hidden"
                        : ""} />
                <div
                    className={this.state.RemotePort_check
                        ? "alert alert-danger hidden"
                        : "alert alert-danger "}
                    role="alert">{Global.GetLocal("端口范围")}</div>
            </div>
        </div>;
        let content = [];
        content.push(
            <div>
                <div className="form-group">
                    <label className="col-xs-3 control-label">{Global.GetLocal("网口选择")}</label>
                    <div className="col-xs-8">
                        <select
                            className="form-control"
                            name="NetNum"
                            value={this.state.NetNum}
                            onChange={e => this.handleChange(e)}>
                            <option value='0'>{Global.GetLocal("全部")}</option>
                            <option value='1'>1</option>
                            <option value='2'>2</option>
                        </select>
                    </div>
                </div>

            </div>
        );
        if (this.state.ServiceType == 'TCPClient' || this.state.ServiceType == 'UDP') {
            content.push(localportview, removeIPview, removeportview);

        } else if (this.state.ServiceType == 'TCPServer') {
            content.push(localportview);

        }
        //心跳包设置
        var xintiao: any;
        // console.log("心跳:" + this.state.ISHeartbeat);
        if (this.state.ISHeartbeat) {
            xintiao = <div>
                <div
                    className={this.state.Heartbeat_Interval_check
                        ? "form-group "
                        : "form-group has-error has-feedback"}>
                    <label className="col-xs-3 control-label">{Global.GetLocal("心跳包时间间隔")}</label>
                    <div className="col-xs-8">
                        <input
                            type="text"
                            className="form-control"
                            placeholder=" "
                            value={this.state.Heartbeat_Interval}
                            name="Heartbeat_Interval"
                            onChange={e => this.handleChange(e)} />
                        <span
                            className={this.state.Heartbeat_Interval_check
                                ? "hidden"
                                : "glyphicon glyphicon-remove form-control-feedback"}></span>
                        <br
                            className={this.state.Heartbeat_Interval_check
                                ? "hidden"
                                : ""} />
                        <div
                            className={this.state.Heartbeat_Interval_check
                                ? "alert alert-danger hidden"
                                : "alert alert-danger "}
                            role="alert">{Global.GetLocal("请输入正确的数值")}</div>
                    </div>
                </div>
                <div
                    className={this.state.Heartbeat_Hex_check
                        ? "form-group "
                        : "form-group has-error has-feedback"}>
                    <label className="col-xs-3 control-label">{Global.GetLocal("心跳包标识")}</label>
                    <div className="col-xs-8">
                        <input
                            type="text"
                            className="form-control"
                            placeholder=" "
                            value={this.state.Heartbeat_Hex}
                            name="Heartbeat_Hex"
                            onChange={e => this.handleChange(e)} />
                        <span
                            className={this.state.Heartbeat_Hex_check
                                ? "hidden"
                                : "glyphicon glyphicon-remove form-control-feedback"}></span>
                        <br
                            className={this.state.Heartbeat_Hex_check
                                ? "hidden"
                                : ""} />
                        <div
                            className={this.state.Heartbeat_Hex_check
                                ? "alert alert-danger hidden"
                                : "alert alert-danger "}
                            role="alert">{Global.GetLocal("请输入正确的标识")}</div>
                    </div>
                </div>
            </div >;

        }
        let dilog = (

            <div className="modal fade" ref="mymodal">
                <div className="modal-dialog">
                    <div className="modal-content">
                        <div className="modal-header">
                            <button type="button" className="close" data-dismiss="modal">
                                <span aria-hidden="true">&times;</span>
                                <span className="sr-only">Close</span>
                            </button>
                            <h4 className="modal-title">{Global.GetLocal("配置网络服务")}</h4>
                        </div>
                        <div className="modal-body">

                            <form action="" method="POST" className="form-horizontal" role="form">

                                <div className="form-group">
                                    <label className="col-xs-3 control-label">{Global.GetLocal("服务类型")}</label>
                                    <div className="col-xs-8">
                                        <select
                                            className="form-control"
                                            value={this.state.ServiceType}
                                            name="ServiceType"
                                            onChange={e => this.handleChange(e)}>

                                            <option key='0'>TCPClient</option>
                                            <option key='1'>TCPServer</option>
                                            <option key='2'>UDP</option>
                                        </select>
                                    </div>
                                </div>
                                {content}
                                <div className="form-group">
                                    <label className="col-xs-3 control-label">{Global.GetLocal("心跳包")}</label>
                                    <div className="col-xs-8">
                                        <label className="form-control  "><input
                                            name="ISHeartbeat"
                                            type="checkbox"
                                            checked={this.state.ISHeartbeat}
                                            onChange={e => this.handleChange(e)} />{Global.GetLocal("启用")}</label>
                                    </div>
                                </div>
                                {xintiao}
                            </form>

                        </div>
                        <div className="modal-footer">

                            <button type="button" className="btn btn-default" data-dismiss="modal">{Global.GetLocal("取消")}</button>
                            <button
                                type="button"
                                name="savebtn"
                                className="btn btn-primary"
                                disabled={!_ischeck}
                                onClick={e => this.handleClick(e)}>{Global.GetLocal("保存")}</button>
                        </div>
                    </div>
                </div>
            </div>
        );
        //////////////////////////////////////////////信息显示
        if (this.props.Servicefg) {
            let servicemtxt = [];
            let titleclassname = "col-xs-6";
            let contentclassname = "col-xs-6";
            servicemtxt.push(
                <div>
                    <div className={titleclassname}>{Global.GetLocal("服务类型")}</div>
                    <div className={contentclassname}>{this.props.Servicefg.ServiceType}</div>
                    <div className="clearfix "></div>
                    <div className={titleclassname}>{Global.GetLocal("网口选择")}</div>
                    <div className={contentclassname}>{this.props.Servicefg.NetNum == "0" ? Global.GetLocal("全部") : this.props.Servicefg.NetNum}</div>
                    <div className="clearfix "></div>
                </div>

            );
            if (this.props.Servicefg.ServiceType == 'UDP') {
                servicemtxt.push(
                    <div>
                        <span className={titleclassname}>{Global.GetLocal("目的IP地址")}</span>
                        <span className={contentclassname}>{this.props.Servicefg.RemoteIP}</span>
                        <div className="clearfix "></div>
                        <span className={titleclassname}>{Global.GetLocal("目的端口")}</span>
                        <span className={contentclassname}>{this.props.Servicefg.RemotePort}</span>
                        <div className="clearfix "></div>
                    </div>

                );
            } else if (this.props.Servicefg.ServiceType == 'TCPClient') {
                servicemtxt.push(
                    <div>
                        <span className={titleclassname}>{Global.GetLocal("本地端口")}</span>
                        <span className={contentclassname}>{this.props.Servicefg.LocalPort}</span>
                        <div className="clearfix "></div>
                        <span className={titleclassname}>{Global.GetLocal("目的IP地址")}</span>
                        <span className={contentclassname}>{this.props.Servicefg.RemoteIP}</span>
                        <div className="clearfix "></div>
                        <span className={titleclassname}>{Global.GetLocal("目的端口")}</span>
                        <span className={contentclassname}>{this.props.Servicefg.RemotePort}</span>
                        <div className="clearfix "></div>
                    </div>

                );
            } else if (this.props.Servicefg.ServiceType == 'TCPServer') {
                servicemtxt.push(
                    <div>
                        <span className={titleclassname}>{Global.GetLocal("本地端口")}</span>
                        <span className={contentclassname}>{this.props.Servicefg.LocalPort}</span>
                        <div className="clearfix "></div>
                    </div>

                );
            }

            let panelclassname: string = '';
            panelclassname = "panel " + (this.props.Servicefg.IsOn
                ? 'panel-info '
                : 'panel-danger ');
            let btntoggle: any;
            if (this.props.Servicefg.IsOn) {
                btntoggle = <button
                    type="button"
                    name="btn_toggle"
                    className="btn btn-default "
                    onClick={e => this.handleClick(e)}>
                    <span className="  glyphicon glyphicon-ban-circle"></span>&nbsp;{Global.GetLocal("禁用")}</button>;
            } else {
                btntoggle = <button
                    type="button"
                    name="btn_toggle"
                    className="btn btn-default "
                    onClick={e => this.handleClick(e)}>
                    <span className=" glyphicon glyphicon-play"></span>&nbsp;{Global.GetLocal("启用")}</button>;
            }

            return (

                <div className="col-xs-12 col-sm-6 col-lg-4">
                    <div className={panelclassname}>

                        <div className="panel-heading">
                            <h1 className="panel-title InlineBlock">

                                <button
                                    name="edit"
                                    type="button"
                                    className="btn btn-default "
                                    onClick={e => this.handleClick(e)}>
                                    <span className="  glyphicon glyphicon-cog"></span>&nbsp;{Global.GetLocal("编辑")}</button>&nbsp; {btntoggle}
                                <button
                                    type="button"
                                    name="btn_del"
                                    className="btn btn-default pull-right"
                                    onClick={e => this.handleClick(e)}>
                                    <span className=" glyphicon glyphicon-trash"></span>&nbsp;{Global.GetLocal("删除")}</button>
                                <MessageBox
                                    ref="messagebox"
                                    Title={Global.GetLocal("警告")}
                                    Content={Global.GetLocal("确定删除")}
                                    Ok={event => this.handleClick(event, "delservice")} />
                            </h1>
                        </div>

                        <div
                            className="panel-body"
                            style={{
                                minHeight: "120px"
                            }}>

                            {servicemtxt}
                            {dilog}

                        </div>
                    </div>
                </div>
            );
        } else {
            //未添加  显示添加按钮
            return (

                <div className="col-xs-12 col-sm-6 col-lg-4">
                    <div className="panel panel-info ">

                        <div className="panel-heading">
                            <h1 className="panel-title InlineBlock">{Global.GetLocal("服务")}&nbsp; &nbsp;

                            </h1>
                        </div>

                        <div
                            className="panel-body"
                            style={{
                                minHeight: "120px"
                            }}>

                            <button
                                type="button"
                                style={{
                                    fontSize: 20
                                }}
                                className={`btn btn-large btn-block btn-default ${Mycss.fillparent}`}
                                name="add"
                                onClick={e => this.handleClick(e)}><span className="glyphicon glyphicon-plus" />{Global.GetLocal("添加")}</button>
                            {dilog}

                        </div>
                    </div>
                </div>
            );
        }

    }
}

//export default Service;